package cn.sdhuijin.vms.service;

import javax.inject.Inject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.sdhuijin.vms.dao.ILeaveDao;
import cn.sdhuijin.vms.dao.IPersonDao;
import cn.sdhuijin.vms.model.Leave;
import cn.sdhuijin.vms.model.Organization;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.model.User;
import cn.sdhuijin.vms.util.OrgUtil;

@Service
public class LeaveService implements ILeaveService {
	final Logger logger = LoggerFactory.getLogger(LeaveService.class);
	@Inject
	private ILeaveDao leaveDao;
	@Inject
	private IPersonDao personDao;

	@Override
	public Page<Leave> getList(Integer page, Integer rows) {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.hasRole("admin")) {
			return leaveDao.findAll(new PageRequest(page, rows, new Sort(
					Direction.DESC, "date")));
		} else {
			Organization org = ((User) currentUser.getPrincipal())
					.getOrganization();
			return leaveDao.findByPersonOrganizationIdIn(
					OrgUtil.getAllIds(org), new PageRequest(page, rows,
							new Sort(Direction.DESC, "date")));
		}
	}

	@Override
	public void save(Long personId, Leave leave) {
		Person person = personDao.findOne(personId);
		if (person != null) {
			leave.setPerson(person);
			this.save(leave);
		} else {
			logger.error("人员{}不存在。", personId);
		}
	}

	@Override
	public void save(Leave leave) {
		leaveDao.save(leave);
	}

	@Override
	public Leave load(Long leaveId) {
		return leaveDao.findOne(leaveId);
	}

}
